<template>
  <div class="online-service">
    <!-- 客服按钮 -->
    <el-button
      v-if="!showChat"
      circle
      type="primary"
      size="large"
      class="service-button"
      @click="toggleChat"
    >
      <el-icon><Service /></el-icon>
    </el-button>

    <!-- 聊天窗口 -->
    <transition name="slide-up">
      <div v-if="showChat" class="chat-window">
        <!-- 聊天头部 -->
        <div class="chat-header">
          <div class="header-info">
            <el-avatar :size="32" :src="serviceInfo.avatar">
              {{ serviceInfo.name.charAt(0) }}
            </el-avatar>
            <div class="service-details">
              <div class="service-name">{{ serviceInfo.name }}</div>
              <div class="service-status">
                <span class="status-dot" :class="{ online: serviceInfo.online }"></span>
                {{ serviceInfo.online ? '在线' : '离线' }}
              </div>
            </div>
          </div>
          
          <div class="header-actions">
            <el-button circle size="small" @click="minimizeChat">
              <el-icon><Minus /></el-icon>
            </el-button>
            <el-button circle size="small" @click="closeChat">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>

        <!-- 聊天内容 -->
        <div class="chat-content" ref="chatContentRef">
          <div class="welcome-message">
            <div class="welcome-text">
              <h4>欢迎使用在线客服</h4>
              <p>我是您的专属学习顾问，有任何问题都可以咨询我哦～</p>
            </div>
          </div>

          <!-- 快捷问题 -->
          <div v-if="messages.length === 0" class="quick-questions">
            <div class="quick-title">常见问题</div>
            <div class="question-list">
              <div 
                v-for="question in quickQuestions" 
                :key="question.id"
                class="question-item"
                @click="sendQuickQuestion(question)"
              >
                {{ question.text }}
              </div>
            </div>
          </div>

          <!-- 消息列表 -->
          <div class="message-list">
            <div 
              v-for="message in messages" 
              :key="message.id"
              class="message-item"
              :class="{ 'message-user': message.type === 'user' }"
            >
              <div class="message-avatar">
                <el-avatar :size="28" :src="message.avatar">
                  {{ message.sender.charAt(0) }}
                </el-avatar>
              </div>
              
              <div class="message-content">
                <div class="message-bubble">
                  <div v-if="message.type === 'text'" class="text-content">
                    {{ message.content }}
                  </div>
                  
                  <div v-else-if="message.type === 'image'" class="image-content">
                    <img :src="message.content" :alt="message.alt" />
                  </div>
                  
                  <div v-else-if="message.type === 'link'" class="link-content">
                    <a :href="message.url" target="_blank">{{ message.content }}</a>
                  </div>
                </div>
                
                <div class="message-time">
                  {{ formatTime(message.timestamp) }}
                </div>
              </div>
            </div>
          </div>

          <!-- 输入提示 -->
          <div v-if="isTyping" class="typing-indicator">
            <div class="typing-avatar">
              <el-avatar :size="28" :src="serviceInfo.avatar">
                {{ serviceInfo.name.charAt(0) }}
              </el-avatar>
            </div>
            <div class="typing-content">
              <div class="typing-dots">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>

        <!-- 聊天输入 -->
        <div class="chat-input">
          <div class="input-tools">
            <el-button circle size="small" @click="showEmoji = !showEmoji">
              <el-icon><Sunny /></el-icon>
            </el-button>
            <el-button circle size="small" @click="selectFile">
              <el-icon><Paperclip /></el-icon>
            </el-button>
          </div>
          
          <div class="input-area">
            <el-input
              v-model="inputMessage"
              type="textarea"
              :rows="2"
              placeholder="输入您的问题..."
              @keyup.enter="sendMessage"
              @keyup.ctrl.enter="sendMessage"
            />
          </div>
          
          <div class="input-actions">
            <el-button 
              type="primary" 
              :disabled="!inputMessage.trim()"
              @click="sendMessage"
            >
              发送
            </el-button>
          </div>
        </div>

        <!-- 表情面板 -->
        <div v-if="showEmoji" class="emoji-panel">
          <div 
            v-for="emoji in emojis" 
            :key="emoji"
            class="emoji-item"
            @click="insertEmoji(emoji)"
          >
            {{ emoji }}
          </div>
        </div>
      </div>
    </transition>

    <!-- 文件上传 -->
    <input
      ref="fileInputRef"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleFileUpload"
    />
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, onUnmounted } from 'vue'
import { 
  Service, Minus, Close, Sunny, Paperclip
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 响应式数据
const showChat = ref(false)
const showEmoji = ref(false)
const isTyping = ref(false)
const inputMessage = ref('')
const messages = ref([])
const chatContentRef = ref()
const fileInputRef = ref()

// 客服信息
const serviceInfo = ref({
  name: '小智助手',
  avatar: '/images/service-avatar.jpg',
  online: true
})

// 快捷问题
const quickQuestions = ref([
  { id: 1, text: '如何注册账号？' },
  { id: 2, text: '忘记密码怎么办？' },
  { id: 3, text: '如何购买课程？' },
  { id: 4, text: '课程有效期多久？' },
  { id: 5, text: '如何申请退款？' },
  { id: 6, text: '联系人工客服' }
])

// 表情列表
const emojis = ref([
  '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣',
  '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰',
  '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜',
  '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳', '😏'
])

// 方法
const toggleChat = () => {
  showChat.value = !showChat.value
  if (showChat.value) {
    nextTick(() => {
      scrollToBottom()
    })
  }
}

const minimizeChat = () => {
  showChat.value = false
}

const closeChat = () => {
  showChat.value = false
  showEmoji.value = false
}

const sendMessage = () => {
  if (!inputMessage.value.trim()) return

  const message = {
    id: Date.now(),
    type: 'text',
    content: inputMessage.value,
    sender: '我',
    avatar: '/images/user-avatar.jpg',
    timestamp: new Date(),
    messageType: 'user'
  }

  messages.value.push(message)
  inputMessage.value = ''
  
  nextTick(() => {
    scrollToBottom()
  })

  // 模拟客服回复
  simulateServiceReply(message.content)
}

const sendQuickQuestion = (question) => {
  inputMessage.value = question.text
  sendMessage()
}

const simulateServiceReply = (userMessage) => {
  isTyping.value = true
  
  setTimeout(() => {
    isTyping.value = false
    
    let replyContent = '感谢您的咨询，我来为您解答。'
    
    // 根据用户消息内容生成不同回复
    if (userMessage.includes('注册')) {
      replyContent = '注册很简单哦！点击右上角的"注册"按钮，填写手机号和密码即可完成注册。'
    } else if (userMessage.includes('密码')) {
      replyContent = '如果忘记密码，可以在登录页面点击"忘记密码"，通过手机验证码重置密码。'
    } else if (userMessage.includes('课程') || userMessage.includes('购买')) {
      replyContent = '您可以在课程详情页点击"立即购买"按钮，支持微信、支付宝等多种支付方式。'
    } else if (userMessage.includes('退款')) {
      replyContent = '课程购买后7天内可申请退款，请联系人工客服处理退款事宜。'
    } else if (userMessage.includes('人工')) {
      replyContent = '正在为您转接人工客服，请稍候...'
    }
    
    const reply = {
      id: Date.now(),
      type: 'text',
      content: replyContent,
      sender: serviceInfo.value.name,
      avatar: serviceInfo.value.avatar,
      timestamp: new Date(),
      messageType: 'service'
    }
    
    messages.value.push(reply)
    
    nextTick(() => {
      scrollToBottom()
    })
  }, 1000 + Math.random() * 2000)
}

const selectFile = () => {
  fileInputRef.value?.click()
}

const handleFileUpload = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过5MB')
    return
  }
  
  const reader = new FileReader()
  reader.onload = (e) => {
    const message = {
      id: Date.now(),
      type: 'image',
      content: e.target.result,
      alt: file.name,
      sender: '我',
      avatar: '/images/user-avatar.jpg',
      timestamp: new Date(),
      messageType: 'user'
    }
    
    messages.value.push(message)
    
    nextTick(() => {
      scrollToBottom()
    })
    
    // 模拟客服回复
    setTimeout(() => {
      const reply = {
        id: Date.now(),
        type: 'text',
        content: '我已收到您发送的图片，正在为您分析...',
        sender: serviceInfo.value.name,
        avatar: serviceInfo.value.avatar,
        timestamp: new Date(),
        messageType: 'service'
      }
      
      messages.value.push(reply)
      
      nextTick(() => {
        scrollToBottom()
      })
    }, 1000)
  }
  
  reader.readAsDataURL(file)
  event.target.value = ''
}

const insertEmoji = (emoji) => {
  inputMessage.value += emoji
  showEmoji.value = false
}

const scrollToBottom = () => {
  if (chatContentRef.value) {
    chatContentRef.value.scrollTop = chatContentRef.value.scrollHeight
  }
}

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生命周期
onMounted(() => {
  // 可以在这里初始化WebSocket连接等
})

onUnmounted(() => {
  // 清理资源
})
</script>

<style lang="scss" scoped>
.online-service {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

.service-button {
  width: 60px;
  height: 60px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  
  .el-icon {
    font-size: 24px;
  }
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 25px rgba(0, 0, 0, 0.2);
  }
}

.chat-window {
  position: absolute;
  bottom: 80px;
  right: 0;
  width: 350px;
  height: 500px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 40px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: var(--el-color-primary);
  color: white;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.service-details {
  .service-name {
    font-weight: 500;
    margin-bottom: 2px;
  }
  
  .service-status {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    opacity: 0.9;
    
    .status-dot {
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background: #ccc;
      
      &.online {
        background: #4ade80;
      }
    }
  }
}

.header-actions {
  display: flex;
  gap: 4px;
  
  .el-button {
    background: rgba(255, 255, 255, 0.1);
    border: none;
    color: white;
    
    &:hover {
      background: rgba(255, 255, 255, 0.2);
    }
  }
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.welcome-message {
  text-align: center;
  margin-bottom: 20px;
  
  .welcome-text {
    h4 {
      margin-bottom: 8px;
      color: var(--el-text-color-primary);
    }
    
    p {
      font-size: 14px;
      color: var(--el-text-color-secondary);
      margin: 0;
    }
  }
}

.quick-questions {
  margin-bottom: 20px;
  
  .quick-title {
    font-size: 14px;
    font-weight: 500;
    margin-bottom: 12px;
    color: var(--el-text-color-primary);
  }
  
  .question-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  
  .question-item {
    padding: 8px 12px;
    background: var(--el-fill-color-extra-light);
    border-radius: 6px;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
      background: var(--el-color-primary-light-9);
      color: var(--el-color-primary);
    }
  }
}

.message-list {
  .message-item {
    display: flex;
    gap: 8px;
    margin-bottom: 16px;
    
    &.message-user {
      flex-direction: row-reverse;
      
      .message-content {
        align-items: flex-end;
        
        .message-bubble {
          background: var(--el-color-primary);
          color: white;
        }
      }
    }
  }
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.message-bubble {
  padding: 8px 12px;
  background: var(--el-fill-color-extra-light);
  border-radius: 12px;
  margin-bottom: 4px;
  
  .text-content {
    font-size: 14px;
    line-height: 1.4;
  }
  
  .image-content img {
    max-width: 100%;
    border-radius: 6px;
  }
  
  .link-content a {
    color: var(--el-color-primary);
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
}

.message-time {
  font-size: 11px;
  color: var(--el-text-color-placeholder);
  padding: 0 4px;
}

.typing-indicator {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.typing-content {
  padding: 8px 12px;
  background: var(--el-fill-color-extra-light);
  border-radius: 12px;
}

.typing-dots {
  display: flex;
  gap: 4px;
  
  span {
    width: 6px;
    height: 6px;
    background: var(--el-text-color-placeholder);
    border-radius: 50%;
    animation: typing 1.4s infinite ease-in-out;
    
    &:nth-child(1) { animation-delay: -0.32s; }
    &:nth-child(2) { animation-delay: -0.16s; }
  }
}

.chat-input {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  padding: 12px 16px;
  border-top: 1px solid var(--el-border-color-extra-light);
}

.input-tools {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.input-area {
  flex: 1;
  
  :deep(.el-textarea__inner) {
    resize: none;
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 6px;
  }
}

.input-actions {
  display: flex;
  align-items: flex-end;
}

.emoji-panel {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 8px;
  padding: 12px 16px;
  border-top: 1px solid var(--el-border-color-extra-light);
  max-height: 120px;
  overflow-y: auto;
}

.emoji-item {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 4px;
  
  &:hover {
    background: var(--el-fill-color-light);
  }
}

.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s ease;
}

.slide-up-enter-from {
  opacity: 0;
  transform: translateY(20px) scale(0.95);
}

.slide-up-leave-to {
  opacity: 0;
  transform: translateY(20px) scale(0.95);
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

@media (max-width: 480px) {
  .chat-window {
    width: 300px;
    height: 450px;
  }
  
  .online-service {
    bottom: 15px;
    right: 15px;
  }
}
</style>
